﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using BYRBBS.Model;
using System.Xml.Linq;
using System.Diagnostics;
using System.Xml.Serialization;
using System.IO;

namespace BYRBBS.Util
{
    public class ParseUtil
    {
        public static T ParseXml<T>(string parseString,out string message)
            ////parseString  为网络请求回来的xml，message用于解析失败后返回的信息
            ////如果密码或用户名错误，返回值为null，否则T对象
        {
            T obj;
            byte[]   bs =   System.Text.Encoding.UTF8.GetBytes(parseString);
            MemoryStream ms = new MemoryStream(bs);
            message = "";
            XDocument doc = XDocument.Parse(parseString);
            if (((XElement)doc.FirstNode).Name != "error")
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                obj =(T)xmlSerializer.Deserialize(ms);
            }
            else
            {
                foreach (XElement item in doc.Descendants("error").Nodes())
                {
                    if (item.Name == "msg")
                    {
                        message = item.Value;
                    }
                }
                return default(T);
            }
            return obj;
        }
    }
}
